<?php

class RateLimit extends Eloquent {

	protected $table = 'rate_limit';
	protected $fillable = array ('method', 'url', 'ip', 'username');

	/**
	 * Rate limit 规则: 
	 * - 1 minute 10 times
	 * - 60 minutes 100 times
	 * 
	 * @param method 		访问的方法
	 * @param url 			访问的url
	 * @param ip 			ip地址
	 * @param username 		用户名
	 * @param period 		在一段时间里面
	 * @param limit 		访问次数上限
	 */
	public static function reachesRateLimit($method, $url, $ip, $username, $period = 60, $limit = 10) {
		if ($method == "GET") {
			return false;
		}
		$count = $query = RateLimit::whereIn('method', array('POST', 'DELETE', 'PUT', 'PATCH'))
			->where('url', $url)
			->where('created_at', '>', date('Y-m-d H:i:s', time()-$period))
			->where(function ($query) use ($ip, $username) {
				$query->where('ip', $ip)->orwhere('username', $username);
			})->count();
		return (bool)($count > $limit);
	}

	/**
	 * 记录访问的数据
	 * 
	 * @param method 		访问的方法
	 * @param url 			访问的url
	 * @param ip 			ip地址
	 * @param username 		用户名
	 */
	public static function logAccess($method, $url, $ip, $username) {
		$result = RateLimit::create ( 
			array (
				'method' => $method, 
				'url' => $url, 
				'ip' => $ip,
				'username' => $username
			) 
		);
		$result->save ();
	}
}